import React, { useEffect, useReducer, useState } from 'react'
import { Toast ,NavBar } from 'antd-mobile';
import Header from "../../components/Header";
import { Cartadd, Getgoodsinfo } from "../../http/api"
import { initState, reducer } from "../Login/user"
import { Link } from "react-router-dom";
import qs from "querystring"
import "./details/details.less"

export default function Detail(props) {
    //初始值
    const [details, setDetail] = useState([]);
    const [state] = useReducer(reducer, initState)
    useEffect(() => {
        let search = props.location.search
        let myURL = new URL("http://localhost:3000"+search)
        let id = myURL.searchParams.get("id")
        //请数据
        Getgoodsinfo({ id }).then((res) => {
            setDetail(res.data.list[0])
        })
    }, [])

    //加入购物车
    const addShop = () => {
        let search = props.location.search
        let type = qs.parse(search.slice(1))
        console.log(type);
        Cartadd({
            uid: state.info.uid,
            type:type.type,
            goodsid: type.id,
            num: details.discount
        }).then(res => {
            if (res.data.code === 200) {
                Toast.info(res.data.msg)
            }
        })
    };
    
    return (
        <div>
            <Header title="商品详情" back></Header>
            <div className="details">
                <img src={details.img} alt="" />
                <p>{details.goodsname}</p>
                <p className="price">￥{details.price}</p>
                <i>{details.description}</i>
            </div>

            <NavBar onClick={() => addShop()}>加入购物车</NavBar>
            <Link to="/index/shop">前往购物车</Link>
        </div>
    )
}
